package com.sohu.sip.group.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sohu.sip.group.Config;
import com.sohu.sip.group.util.StringUtil;

public abstract class AbstractCacheRPC {

	/**
	 * Logger for this class
	 */
	protected final Log log = LogFactory.getLog(getClass());

//	protected static final String RPC_GROUP = "AdsenderRPCGroup";
	
	protected static final String RPC_GROUP_NAME_PROPERTIES = "cache.rpc.group.name";

	private static final String DEFAULT_RPC_CHANNEL_PROPERTIES_PRE = "UDP(mcast_addr=";

	private static final String DEFAULT_RPC_CHANNEL_PROPERTIES_POST = ";mcast_port=42266;ip_ttl=32;mcast_send_buf_size=2097152;mcast_recv_buf_size=2097152;ucast_send_buf_size=2097152;ucast_recv_buf_size=2097152):PING(num_initial_members=2;timeout=3000):MERGE2:FD(timeout=5000;max_tries=5;shun=false):VERIFY_SUSPECT(timeout=5000):pbcast.NAKACK(gc_lag=10;retransmit_timeout=300,600,1200,2400,4800;max_xmit_size=8192):pbcast.STABLE(desired_avg_gossip=20000):UNICAST(timeout=600,1200,2400,4800):FRAG(frag_size=8192;down_thread=false;up_thread=false):pbcast.GMS(print_local_addr=true;join_timeout=5000;join_retry_timeout=2000;shun=false):pbcast.STATE_TRANSFER";

	private static final String DEFAULT_RPC_MULTICAST_IP = "230.12.21.132";

	protected static final int DEFAULT_RPC_PORT = 10020;

	private static final String RPC_MULTICAST_IP_PROPERTY = "cache.rpc.multicast.ip";

	private static final String RPC_CHANNEL_PROPERTIES = "cache.rpc.properties";

	private static final String RPC_PORT_PROPERTY = "cache.rpc.server.port";

	protected String getRpcProperties(Config config, boolean server) {
		
		String rpcProperties = config.getProperty(RPC_CHANNEL_PROPERTIES);
		if (rpcProperties != null) {
			log.info("Starting a RPC server with cache.rpc.properties=" + rpcProperties);
			return rpcProperties.trim();
		}

		String rpcMulticastIP = config.getProperty(RPC_MULTICAST_IP_PROPERTY);
		if (rpcMulticastIP == null) {
			rpcMulticastIP = DEFAULT_RPC_MULTICAST_IP;
		}

		int rpcPort = StringUtil.parseInt(
				config.getProperty(RPC_PORT_PROPERTY), DEFAULT_RPC_PORT);

		if (server == true) {
			rpcProperties = DEFAULT_RPC_CHANNEL_PROPERTIES_PRE
					+ rpcMulticastIP.trim() + ";bind_port=" + rpcPort
					+ DEFAULT_RPC_CHANNEL_PROPERTIES_POST;
			log.info("Starting a RPC server with properties=" + rpcProperties);
		} else {
			rpcProperties = DEFAULT_RPC_CHANNEL_PROPERTIES_PRE
					+ rpcMulticastIP.trim()
					+ DEFAULT_RPC_CHANNEL_PROPERTIES_POST;
			log.info("Starting a RPC client with properties=" + rpcProperties);
		}

		return rpcProperties;

	}

}
